﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Rechargeable.Amazon.Products
{
    public class ProductAppService : CrudAppService<Product, ProductDto, long, PagedAndSortedResultRequestProductDto,
        ProductDto,
        ProductDto>, IProductAppService
    {
        public ProductAppService(IRepository<Product, long> repository) : base(repository)
        {
        }

        public override async Task<ProductDto> CreateAsync(ProductDto input)
        {
            var product = await Repository.FindAsync(q => q.Asin == input.Asin);
            if (product == null)
            {
                input.Count = 1;
                product = MapToEntity(input);
                return await base.CreateAsync(input);
            }
            else
            {
                input.Count = product.Count+1;
                input.Name = product.Name;
                //Repository.UpdateAsync(product);
                return await base.UpdateAsync(product.Id, input);
            }
        }

        protected override async Task<IQueryable<Product>> CreateFilteredQueryAsync(PagedAndSortedResultRequestProductDto input)
        {
            var query = await base.CreateFilteredQueryAsync(input);
            return query.WhereIf(!string.IsNullOrEmpty(input.Asin), q => q.Asin == input.Asin);
        }
    }
}
